package cn.xspace.wnx.activity;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BBizList;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class FeedInfoEditActivity extends BaseActivity {

    public static final String TAG = FeedInfoEditActivity.class.getSimpleName();
    public static final String TYPE_EDIT = "edit";
    public static final String TYPE_DELETE = "delete";
    public static final String TYPE_ADD = "add";

    private TitleBar mTitleBar;
    private RelativeLayout mRlAnimalUse;
    private RelativeLayout mRlAnimalType;
    private TextView mTvAnimalType;
    private TextView mTvAnimalUse;
    private EditText mEtAnimalCount;
    private LinearLayout mLayoutDelete;
    private Button mBtDelete;

    private boolean isEditInfo;
    private String breed_code;
    private String object_type;

    private List<BBizList> animalTypeList;//当前选中的动物种类列表
    private List<BBizList> animalUseList;//当前选中的动物用途列表
    private BBizList animalInfoBean;
    private ArrayList<BBizList> animalInfoBeanList = new ArrayList<>();
    private AlertDialog alertDialog;
    private BBizList oldBean;//中转变量,删除时使用,避免编辑了之后再点击删除,删除的为编辑后的内容
    private int editPosition;//编辑的是哪一个条目

    private String user_id;
    private String plat_code;
    private String user_areacode;

    @Override
    protected void getIntentData() {
        isEditInfo = getIntent().getBooleanExtra(IntentConstant.isEditInfo, false);
        breed_code = getIntent().getStringExtra(IntentConstant.breed_code);
        object_type = getIntent().getStringExtra(IntentConstant.object_type);
        if (!isEditInfo) {
            animalInfoBean = new BBizList();
            Serializable serializableExtra = getIntent().getSerializableExtra(IntentConstant.animalInfoBeanList);
            animalInfoBeanList.addAll((ArrayList<BBizList>) serializableExtra);
        } else {
            animalInfoBean = (BBizList) getIntent().getSerializableExtra(IntentConstant.animalInfoBean);
            editPosition = getIntent().getIntExtra(IntentConstant.editPosition, -1);
//            animalInfoBean = new BBizList(oldBean);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_feed_info_edit);
    }

    @Override
    protected void initFindViewById() {
        mRlAnimalUse = (RelativeLayout) findViewById(R.id.rl_animal_use);
        mRlAnimalType = (RelativeLayout) findViewById(R.id.rl_animal_type);
        mTvAnimalType = (TextView) findViewById(R.id.txt_add_animal_type);
        mTvAnimalUse = (TextView) findViewById(R.id.txt_add_animal_uses);
        mLayoutDelete = (LinearLayout) findViewById(R.id.layout_delete_feed_info);
        mBtDelete = (Button) findViewById(R.id.bt_delete_feed_info);
        mEtAnimalCount = (EditText) findViewById(R.id.et_animal_amount);
        mTitleBar = (TitleBar) findViewById(R.id.feed_info_title_bar);
        mTitleBar.showRightText();
        if (isEditInfo) {
            mTitleBar.setTitle(getString(R.string.modify_feed_info));
            mTvAnimalType.setText(animalInfoBean.biz_name); //种类
            mTvAnimalUse.setText(animalInfoBean.animal_use_name); //用途
            mEtAnimalCount.setText(animalInfoBean.animal_count);
            mLayoutDelete.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setTitle(getString(R.string.add_feed_info));
        }
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        plat_code = MyInfoUtil.getPlatCode();
        user_areacode = MyInfoUtil.getAppDeptAreaCode();
        requestAnimalTypeData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (isEditInfo) {
//                    DialogHelp.getConfirmDialogWithoutContent(mContext,
//                            getString(R.string.cancel_and_exit),
//                            getString(R.string.think_again_and_again),
//                            getString(R.string.button_ok),
//                            null, new ButtonClickListener() {
//                                @Override
//                                public void buttonClick(View view) {
//                                    finish();
//                                }
//                            }).show();
//                } else {
                finish();
//                }
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveInfo();
            }
        });
        mRlAnimalUse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(animalInfoBean.biz_id)) {
                    T.showSingleL(getString(R.string.please_select_animal_type));
                } else {
                    requestAnimalUseData();
                }
            }
        });
        mRlAnimalType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAnimalTypeDialog();
            }
        });
        mBtDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelp.getConfirmDialogWithoutContent(mContext,
                        getString(R.string.delete_feed_info),
                        getString(R.string.think_again_and_again),
                        getString(R.string.button_ok),
                        null, new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                //TODO 删除某个养殖信息
                                HashMap<String, Object> eventMap = new HashMap<>();
                                eventMap.put(EventBusConstant.TYPE, TAG);
                                eventMap.put(EventBusConstant.ACTION_KEY, TYPE_DELETE);
                                eventMap.put(IntentConstant.editPosition, editPosition);
                                EventBus.getDefault().post(eventMap);
                                finish();
                            }
                        }).show();
            }
        });
    }

    private void saveInfo() {
        if (checkInfo()) { //可以保存了
            //点击保存时设置存栏个数
            animalInfoBean.animal_count = mEtAnimalCount.getText().toString().trim();
            HashMap<String, Object> eventMap = new HashMap<>();
            eventMap.put(EventBusConstant.TYPE, TAG);
            if (isEditInfo) {
                eventMap.put(EventBusConstant.ACTION_KEY, TYPE_EDIT);
                eventMap.put(IntentConstant.editPosition, editPosition);
            } else {
                eventMap.put(EventBusConstant.ACTION_KEY, TYPE_ADD);
            }
            eventMap.put(EventBusConstant.ACTION_VALUE, animalInfoBean);
            EventBus.getDefault().post(eventMap);
            finish();
        }
    }

    private boolean checkInfo() {
        if (TextUtils.isEmpty(animalInfoBean.biz_id)) {
            T.showSingleL(getString(R.string.please_select_animal_type));
            return false;
        } /*else if (TextUtils.isEmpty(animalInfoBean.animal_use_id)) {
            T.showSingleL(getString(R.string.please_select_animal_use)); //用途可以不填写,可能存在没有用途的动物种类
            return false;
        }*/ else if (TextUtils.isEmpty(mEtAnimalCount.getText().toString())) {
            T.showSingleL(getString(R.string.please_select_animal_count));
            return false;
        } else if (!isEditInfo) {
            for (BBizList bBizList : animalInfoBeanList) {
                if (TextUtils.equals(animalInfoBean.biz_id, bBizList.biz_id)) {
                    T.showSingleL(getString(R.string.animal_type_exist));
                    return false;
                }
            }
        }
        return true;
    }

    private void requestAnimalTypeData() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("breed_code", breed_code);
        map.put("object_type", object_type);
        map.put("user_id", user_id);
        map.put("plat_code", plat_code);
        map.put("user_areacode", user_areacode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_ANIMAL, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<BBizList>>() {
                    @Override
                    public List<BBizList> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<BBizList>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<BBizList>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<BBizList> newList) {
                        hideWaitDialog();
                        animalTypeList = new ArrayList<>();
                        animalTypeList.addAll(newList);
//                        showAnimalTypeDialog();
                    }
                });
    }

    private void showAnimalTypeDialog() {
        final String[] arrays = new String[animalTypeList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = animalTypeList.get(j).biz_name;
            if (TextUtils.equals(animalTypeList.get(j).biz_id, animalInfoBean.biz_id)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvAnimalType.setText(arrays[which]);
                        animalInfoBean.biz_id = animalTypeList.get(which).biz_id;
                        animalInfoBean.biz_name = animalTypeList.get(which).biz_name;
                        mTvAnimalUse.setText(R.string.please_select);
                        animalInfoBean.animal_use_id = null;
                        animalInfoBean.animal_use_name = null;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void requestAnimalUseData() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("breed_type", animalInfoBean.biz_id);
        map.put("user_id", user_id);
        map.put("plat_code", plat_code);
        map.put("user_areacode", user_areacode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_ANIMAL_USE, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<BBizList>>() {
                    @Override
                    public List<BBizList> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<BBizList>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<BBizList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<BBizList> newList) {
                        hideWaitDialog();
                        animalUseList = new ArrayList<>();
                        animalUseList.addAll(newList);
                        if (animalUseList.size() == 0) {
                            DialogHelp.getMessageDialog(mContext, getString(R.string.animal_uses_empty)).show();
                            mTvAnimalUse.setText(getString(R.string.is_empty));
                        } else {
                            showAnimalUseDialog();
                        }
                    }
                });
    }

    private void showAnimalUseDialog() {
        final String[] arrays = new String[animalUseList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = animalUseList.get(j).animal_use_name;
            if (TextUtils.equals(animalUseList.get(j).animal_use_id, animalInfoBean.animal_use_id)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvAnimalUse.setText(arrays[which]);//请求结果里面没有code,就不赋值了
                        animalInfoBean.animal_use_id = animalUseList.get(which).animal_use_id;
                        animalInfoBean.animal_use_name = animalUseList.get(which).animal_use_name;
                        alertDialog.dismiss();
                    }
                }).show();
    }
}
